package io;

import basic.JodisList;
import basic.JodisString;
import utils.ByteUtils;
import utils.IoUtils;
import utils.KeyValue;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

public class JdbReader {
    private Path jdbFile;

    public JdbReader(String dir, String fName) throws IOException {
        this.jdbFile = IoUtils.createFileIfNotExists(dir, fName);
    }

    public KeyValue<String, JodisString> readString(ByteBuffer buffer) {
        if (Objects.isNull(buffer)) {
            return new KeyValue<>();
        }

        buffer.flip();
        if (buffer.remaining() < 1) {
            return new KeyValue<>();
        }
        int keyLen = buffer.getInt();
        String key = ByteUtils.toUTF8String(buffer, keyLen);
        int valueLen = buffer.getInt();
        String value = ByteUtils.toUTF8String(buffer, valueLen);
        return new KeyValue<>(key, new JodisString(value));
    }

    public KeyValue<String, JodisList> readList(ByteBuffer buffer) {
        KeyValue<String, List<String>> ans = readCollection(buffer);
        if (ans.isNull()) {
            return new KeyValue<>();
        }
        String key = ans.getKey();
        List<String> value = ans.getValue();
        JodisList jodisList = new JodisList(value);
        return new KeyValue<>(key, jodisList);
    }

    private KeyValue<String, List<String>> readCollection(ByteBuffer buffer) {
        if (Objects.isNull(buffer)) {
            return new KeyValue<>();
        }
        buffer.flip();
        if (buffer.remaining() < 1) {
            return new KeyValue<>();
        }
        int keyLen = buffer.getInt();
        String key = ByteUtils.toUTF8String(buffer, keyLen);
        // 集合长度
        int len = buffer.getInt();
        List<String> value = new ArrayList<>(len);
        for (int i = 0; i < len ; i ++) {
            int itemLen = buffer.getInt();
            String item = ByteUtils.toUTF8String(buffer, itemLen);
            value.add(item);
        }
        return new KeyValue<>(key, value);
    }
}
